﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;
using HYCodeBase.WinForm;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	[Journaling(JournalingMode.NoCommandData)]
	public class InHomePipeTag : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (commandData == null)
			{
				throw new System.ArgumentNullException("ExternalCommandData", "ExternalCommandData is null!");
			}
			if (InHomePipeTag.wndRevit == null)
			{
				InHomePipeTag.wndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)4,
				(ViewType)2
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Transaction transaction = new Transaction(document, "加载共享参数");
			transaction.Start();
			MarkOperation markOperation = new MarkOperation();
			markOperation.AddAllShareParametes(commandData.Application);
			transaction.Commit();
			if ((int)document.ActiveView.ViewType == 4)
			{
				if ((int)document.ActiveView.ViewType == 4 && !(document.ActiveView as View3D).IsLocked)
				{
					YJKMessageBox.Warning("该三维视图无法标注，请锁定视角后再进行此操作！");
					return Autodesk.Revit.UI.Result.Cancelled;
				}
				this.isPlane = false;
			}
			else
			{
				this.isPlane = true;
			}
			int wMsg = 7;
			InHomePipeTag.SendMessage(InHomePipeTag.wndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			FormInHomePipe formInHomePipe = null;
			try
			{
				formInHomePipe = new FormInHomePipe();
				formInHomePipe.Show(InHomePipeTag.wndRevit);
				DimInHomePipe dimInHomePipe = new DimInHomePipe(commandData, formInHomePipe, this.isPlane);
				while (dimInHomePipe.Run())
				{
				}
			}
			catch
			{
			}
			if (formInHomePipe != null)
			{
				formInHomePipe.Close();
			}
			markOperation.SetActiveDocAllLoadedTags(document, false);
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public static WindowHandle wndRevit;

		private bool isPlane = true;
	}
}
